package com.offcn.bigdata.spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Iterator;

/**
 * @Auther: BigData-LGW
 * @ClassName: WordCount
 * @Date: 2020/12/3 22:15
 * @功能描述:
 * @Version:1.0
 */
public class WordCount {
    public static void main(String[] args) {
        //step 1 创建sparkContext
        SparkConf sparkConf = new SparkConf();
        sparkConf.setMaster("local[*]");
        sparkConf.setAppName(WordCount.class.getSimpleName());

        JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf);

        //2.加载外部数据源
        JavaRDD<String> stringJavaRDD = javaSparkContext.textFile("F:/Hello.txt");
        //step 3.基于业务完成各种计算
        JavaRDD<String> words = stringJavaRDD.flatMap(new FlatMapFunction<String, String>() {
            public Iterator<String> call(String s) throws Exception {
                return Arrays.asList(s.split("\\s+")).iterator();
            }
        });
        JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String word) throws Exception {
                return new Tuple2<String, Integer>(word, 1);
            }
        });
        JavaPairRDD<String, Integer> ret = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return integer + integer2;
            }
        });

        //step 4.完成数据的落地
        ret.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> kv) throws Exception {
                System.out.println(kv._1+"------->"+kv._2);
            }
        });
        //step 5.释放资源
        javaSparkContext.stop();
    }
}
